/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙，邂逅框架梦]
 * 
 * https://zhiqim.org/project/zhiqim_framework/zhiqim_orm.htm
 *
 * Zhiqim Orm is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.zhiqim.orm.dbo.condition;

import org.zhiqim.kernel.model.maps.MapSO;
import org.zhiqim.kernel.util.Asserts;
import org.zhiqim.orm.ORMException;
import org.zhiqim.orm.dbo.Condition;
import org.zhiqim.orm.dbo.Dbo;
import org.zhiqim.orm.dbo.DboField;

/**
 * 表达式条件，如where field = field2+1
 *
 * @version v1.0.0 @author zouzhigang 2017-9-8 新建与整理
 */
public class _Expression extends Condition
{
    private String field;
    private String expression;
    private String condition;
    
    public _Expression(String field, String expression, String condition)
    {
        this.field = field;
        this.expression = expression;
        this.condition = condition;
    }
    
    @Override
    public boolean match(Object obj)
    {
        throw Asserts.exception("暂不支持表达式匹配");
    }

    @Override
    public String toSql(Dbo dbo, MapSO paramMap) throws ORMException
    {
        assertField(dbo, field);
        
        String column = dbo.getColumn(field);
        
        //对表达式中可能出现的字段进行匹配，替换成表列，注意有可能第二个列名会包含第一个列名，因此处理时字段名从长到短进行匹配
        DboField[] dboFieldArr = dbo.getFieldColumnListOrderByLen();
        for (DboField dboField : dboFieldArr)
        {//依次从长到短对表达式中的字段替换成表列 TODO 暂不对$等可能替换成错进行处理
            expression = expression.replaceAll(dboField.getField(), dboField.getColumn());
        }

        return new StringBuilder()
            .append(column).append(_SPACE_).append(condition).append(_SPACE_).append(expression)
            .toString();
    }
}
